package com.pxmeta.dynamic.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.pxmeta.circle.entity.Circle;
import com.pxmeta.circle.entity.vo.ParentCircleVO;
import com.pxmeta.circle.service.ICircleService;
import com.pxmeta.circle.service.IUserCircleService;
import com.pxmeta.comment.service.ICommentService;
import com.pxmeta.common.constant.HttpStatus;
import com.pxmeta.common.constant.Status;
import com.pxmeta.common.enums.DynamicEnum;
import com.pxmeta.common.exception.ServiceException;
import com.pxmeta.dynamic.entity.*;
import com.pxmeta.dynamic.entity.dto.*;
import com.pxmeta.dynamic.entity.vo.DraftVideoVO;
import com.pxmeta.dynamic.entity.vo.DynamicDraftVO;
import com.pxmeta.dynamic.entity.vo.TopicVO;
import com.pxmeta.dynamic.entity.vo.VideoVO;
import com.pxmeta.dynamic.mapper.DynamicMapper;
import com.pxmeta.dynamic.service.*;
import com.pxmeta.user.entity.User;
import com.pxmeta.user.entity.dto.UserDTO;
import com.pxmeta.user.entity.vo.NearbyUserVO;
import com.pxmeta.user.mapper.UserMapper;
import com.pxmeta.user.service.IUserFollowService;
import com.pxmeta.user.service.NearbyUserService;
import com.pxmeta.verify.service.VerifyService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 社区内容Service业务层处理
 *
 * @author wcl
 * @date 2022-03-21
 */
@Service
@SuppressWarnings("all")
@Slf4j
@RequiredArgsConstructor
public class CommunityDynamicServiceImpl extends ServiceImpl<DynamicMapper, Dynamic> implements IDynamicService {

    private final DynamicMapper dynamicMapper;
    private final UserMapper userMapper;
    private final ICommunityDynamicUserLikeService dynamicUserLikeService;
    private final ITopicService topicService;
    private final IUserFollowService userFollowService;
    private final ICommentService commentService;
    private final IDynamicDislikeService dislikeService;
    private final ITopicDynamicService topicDynamicService;
    private final ISearchHistoryService searchHistoryService;
    private final VerifyService verifyService;
    private final IAcsClient acsClient;
    private final ICircleService circleService;
    private final IMailService mailService;
    private final IUserCircleService userCircleService;
    private final NearbyUserService nearbyUserService;

    public static final Long AI_DRAW_CIRCLE_ID = 1590568116964024321L;

    @Override
    @SneakyThrows
    public Long publish(Long userId, CreateDynamicDTO dto) {
        long dynamicId = IdWorker.getId();
        Dynamic dynamic = new Dynamic();
        dynamic.setId(dto.getId());
        String audioUrl = dto.getAudioUrl();
        dynamic.setAudioUrl(audioUrl);
        dynamic.setUserId(userId);
        dynamic.setAudioTime(dto.getAudioTime());
        if (dto.getSkillId() != null){
            dynamic.setType(2);//服务
            dynamic.setSkillId(dto.getSkillId());
            dynamic.setPrice(dto.getPrice());
            dynamic.setTitle(dto.getTitle());
            dynamic.setOriginalPrice(dto.getOriginalPrice());
        }else {
            if (StringUtils.isNotBlank(dto.getContent()) && dto.getContent().length() > 8){
                String substring = dto.getContent().substring(0,8);
                dynamic.setTitle(substring + "...");
            }
        }

        String chatGroupId = dto.getChatGroupId();
        if (StringUtils.isNotBlank(chatGroupId)){
            dynamic.setType(1);//群聊
            dynamic.setChatGroupId(chatGroupId);
            dynamic.setChatGroupName(dto.getChatGroupName());
            dynamic.setChatGroupAvatar(dto.getChatGroupAvatar());
            dynamic.setChatGroupUserCount(dto.getChatGroupUserCount());
        }


        dynamic.setContent(dto.getContent());
        dynamic.setAddress(dto.getAddress());
        List<String> imgList = dto.getImgList();
        List<String> videoList = dto.getVideoList();

        boolean haveImgOrVideo = false;
        if (CollectionUtil.isNotEmpty(imgList)) {
            if (imgList.size() > 4) {
                throw new ServiceException("图片数量超出限制！", HttpStatus.PARAMS_ERROR);
            }
            haveImgOrVideo = true;
            String imgUrls = StrUtil.join(",", imgList);
            dynamic.setImgUrls(imgUrls);
        }
        if (CollectionUtil.isNotEmpty(videoList)){
            if (videoList.size() > 4) {
                throw new ServiceException("视频数量超出限制！", HttpStatus.PARAMS_ERROR);
            }
            haveImgOrVideo = true;
            String videoIds = StrUtil.join(",", videoList);
            dynamic.setVideoIds(videoIds);
        }
        if (StringUtils.isNotBlank(audioUrl)){
            haveImgOrVideo = true;
        }
        dynamic.setCircleId(dto.getCircleId()==null?1L:dto.getCircleId());
        dynamic.setViewPermission(dto.getViewPermission());
        dynamic.setStatus(Status.SUCCESS.getValue());

        if (dto.getIsAiDraw()){
            dynamic.setCircleId(AI_DRAW_CIRCLE_ID);
        }
        //是否发布
        if (null != dto.getIsPublish() && !dto.getIsPublish()) {
            dynamic.setStatus(Status.NOT_PUBLISH.getValue());
        }else if (!dto.getIsAiDraw()){
            //判断内容是否为空
            if (!haveImgOrVideo && StringUtils.isBlank(dto.getContent())){
                throw new ServiceException("内容不能为空！",HttpStatus.PARAMS_ERROR);
            }
            Status status = verifyService.audit(Arrays.asList(dto.getContent()), dto.getImgList());
            dynamic.setStatus(status.getValue());
            if (CollectionUtil.isNotEmpty(videoList)){
                //如果视频不为空，则进入机器审核状态
                dynamic.setStatus(Status.ROBOT_PENDING.getValue());
                //机器审核视频
                for (String videoId : videoList) {
                    GetPlayInfoRequest request = new GetPlayInfoRequest();
                    request.setVideoId(videoId);
                    GetPlayInfoResponse response = acsClient.getAcsResponse(request);
                    List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
                    String playURL = playInfoList.get(0).getPlayURL();
                    verifyService.auditVideo(dto.getId() == null?dynamicId:dto.getId(),playURL);
                }
            }
        }
        List<Long> topicIdList = dto.getTopicIdList();
        if (CollectionUtil.isNotEmpty(topicIdList)) {
            String topicIds = StrUtil.join(",", topicIdList);
            dynamic.setTopicIds(topicIds);
        }
        if (dto.getId() != null){
            this.updateById(dynamic);
        }else {
            dynamic.setId(dynamicId);
            this.save(dynamic);
        }
        if (CollectionUtil.isNotEmpty(topicIdList)){
            List<TopicDynamic> tdList = Lists.newLinkedList();
            List<Topic> topicList = topicService.listByIds(topicIdList);
            for (Topic topic : topicList) {
                topic.setUserCount(topic.getUserCount()+1);
            }
            topicService.updateBatchById(topicList);
            for (Long topicId : topicIdList) {
                TopicDynamic td = new TopicDynamic();
                td.setDynamicId(dynamic.getId());
                td.setTopicId(topicId);
                tdList.add(td);
            }
            topicDynamicService.saveBatch(tdList);
        }


        Integer status = dynamic.getStatus();
        //审核通知
        if (Status.ROBOT_PENDING.getValue().equals(status)
                || Status.PENDING.getValue().equals(status)){
            LocalDateTime createTime = dynamic.getCreateTime();
            int month = createTime.getMonth().getValue();
            int day = createTime.getDayOfMonth();
            int hour = createTime.getHour();
            int minute = createTime.getMinute();
            mailService.sendNoticeMessage(userId, dynamic.getCircleId(), String.format("您于%s月%s日%s：%s发布的动态，暂时无法对他人可见，现在正在排队审核中。",month,day,hour,minute));
        }
        return dynamic.getId();
    }


    public static void main(String[] args) {
        String content = "呵呵哈";

        String substring = content.substring(0,8);
        System.out.println(substring);
    }




    @Override
    public List<DynamicDTO> getByCircleId(Long circleId, Long userId, Integer page, Integer size, Integer type, Double userLng, Double userLnt) {
        Circle circle = circleService.getById(circleId);
        Integer circleType = circle.getType();

        List<Long> nearUserIds = Lists.newLinkedList(); //附近的人的 id 集合。
        List<NearbyUserVO> nearbyUserVOS = Lists.newLinkedList();

        List<Long> likeDynamicIds = dynamicUserLikeService.getUserLikeIds(userId);

        List<Long> followUserIds = userFollowService.getFollowUsers(userId, 1, 1000).stream().map(UserDTO::getId).collect(Collectors.toList());


        //获取附近的人
        if (type == 3){
            nearbyUserVOS = nearbyUserService.nearBySearch(50d, userLng, userLnt);
            nearUserIds = nearbyUserVOS.stream().map(NearbyUserVO::getUserId).collect(Collectors.toList());
        }

        List<DynamicDTO> list = baseMapper.getByCircleId(circleId, userId, new Page(page, size), type,circleType, nearUserIds);
        patchData(list,userId);
        for (DynamicDTO dto : list) {
            dto.setIsLike(likeDynamicIds.contains(dto.getId()));
            dto.setIsFollow(followUserIds.contains(dto.getAuthorId()));
        }
        if (CollectionUtil.isNotEmpty(nearUserIds)){
            for (DynamicDTO dto : list) {
                for (NearbyUserVO nearUser : nearbyUserVOS) {
                    if (dto.getAuthorId().equals(nearUser.getUserId())){
                        Double distance = nearUser.getDistance(); //距离
                        dto.setDistance(distance+"km");
                        break;
                    }
                }
            }
        }

        return list;
    }


//    // 实现推荐算法的方法
//    private List<DynamicDTO> recommendPosts(Long circleId, Long userId, Integer page, Integer size, Integer type, Integer circleType, List<Long> nearUserIds) {
//        // 从数据库或其他数据源中获取用户的兴趣标签
//        User user = userMapper.selectById(userId);
//        String tagIds = user.getTagIds();
//
//        // 根据用户的兴趣标签，查询具有相似兴趣的其他用户
//        List<Long> similarUserIds = getSimilarUserIds(userInterests);
//
//        // 获取相似用户的帖子数据
//        List<DynamicDTO> similarUserPosts = baseMapper.getPostsByUserIds(similarUserIds, size * 2); // 获取足够多的帖子数据
//
//        // 过滤掉已经被用户浏览过的帖子
//        List<DynamicDTO> filteredPosts = filterViewedPosts(similarUserPosts, userId);
//
//        // 根据推荐算法的逻辑，对帖子进行排序或打分，获取最终的推荐结果
//        List<DynamicDTO> recommendedPosts = rankAndSelectPosts(filteredPosts, page, size);
//
//        patchData(recommendedPosts, userId);
//
//        return recommendedPosts;
//    }

    @Override
    public List<DynamicDTO> getByTopicId(Long topicId, Long userId, Integer page, Integer size,Integer type) {
        Topic topic = topicService.getById(topicId);
        if (null == topic){
            throw new ServiceException("话题不存在",HttpStatus.PARAMS_ERROR);
        }
        boolean isCircleUser = userCircleService.getIsCircleUser(userId, topic.getCircleId());
        Long viewCount = topic.getViewCount();
        viewCount = viewCount == null ? 1 :viewCount + 1;
        topic.setViewCount(viewCount);
        topicService.updateById(topic);
        List<String> allTopicIds = Lists.newLinkedList();
        List<DynamicDTO> list =  baseMapper.getByTopicId(topicId, userId, new Page<>(page,size), type, isCircleUser);
        this.patchData(list,userId);
        return list;

    }

    @Override
    public List<Dynamic> getBlockedList() {
        LambdaQueryWrapper<Dynamic> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Dynamic::getStatus, Status.FAIL);
        return this.list(wrapper);
    }

    @Override
    public Long getHotDynamicId(Long circleId) {
        return baseMapper.getHotDynamicId(circleId);
    }

    @Override
    public IPage<DynamicDTO> getList( Integer page, Integer size, Integer status) {
        IPage<DynamicDTO> pageList = baseMapper.getList( new Page(page,size),status);
        patchData(pageList.getRecords(),0L);
        return pageList;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void deleteDynamic(Long id) {
        topicDynamicService.deleteByDynamicId(id);
        this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void realDeleteDynamic(Long id) {
        topicDynamicService.deleteByDynamicId(id);
        baseMapper.deleteById(id);
    }


    @Override
    public List<DynamicDTO> getByUserId(Long userId, Integer page, Integer size) {
        LambdaQueryWrapper<Dynamic> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Dynamic::getUserId, userId)
                .eq(Dynamic::getStatus, Status.SUCCESS.getValue());
//        if (circleId != null) {
//            wrapper.eq(Dynamic::getCircleId, circleId)
//                    .eq(Dynamic::getViewPermission,1)
//                    .orderByDesc(Dynamic::getCreateTime);
//        }
        wrapper.orderByDesc(Dynamic::getCreateTime);
        List<Dynamic> dynamicList = this.page(new Page<>(page, size), wrapper).getRecords();
        User user = userMapper.selectById(userId);
        LinkedList<DynamicDTO> list = Lists.newLinkedList();
        for (Dynamic dynamic : dynamicList) {
            DynamicDTO dto = patchData(dynamic, user, true, userId);
            list.add(dto);
        }
        return list;
    }

    @Override
    public List<DynamicDTO> search(Long currentUserId, Long circleId, String keyword, Integer page, Integer size) {
        //保存搜索历史
        searchHistoryService.saveSearch(currentUserId,circleId,keyword, DynamicEnum.TYPE_DYNAMIC.getType());
        List<UserDTO> followUsers = userFollowService.getFollowUsers(currentUserId, 1, 100); //关注的用户
        List<DynamicDTO> list = baseMapper.search(circleId, currentUserId, new Page(page, size), keyword);
        this.patchData(list,currentUserId);
        return list;
    }

    /**
     * 获取上次草稿
     *
     * @param userId
     * @return
     */
    @Override
    @SneakyThrows
    public DynamicDraftVO getDynamicDraft(Long userId) {
        LambdaQueryWrapper<Dynamic> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Dynamic::getUserId, userId)
                .eq(Dynamic::getStatus, Status.NOT_PUBLISH.getValue());
        Dynamic dynamic = this.getOne(wrapper,false);
        if (null != dynamic) {
            DynamicDraftVO vo = new DynamicDraftVO();
            vo.setId(dynamic.getId());
            vo.setAudioUrl(dynamic.getAudioUrl());
            vo.setAddress(dynamic.getAddress());
            vo.setContent(dynamic.getContent());
            String imgUrls = dynamic.getImgUrls();
            String videoIds = dynamic.getVideoIds();
            if (StringUtils.isNotBlank(imgUrls)) {
                List<String> imgList = Arrays.asList(imgUrls.split(","));
                vo.setImgUrls(imgList);
            }
            if (StringUtils.isNotBlank(videoIds)) {
                if (StringUtils.isNotBlank(videoIds)){
                    List<DraftVideoVO> videoList = Lists.newLinkedList();
                    List<String> videoIdList = Arrays.asList(videoIds.split(","));
                    for (String videoId : videoIdList) {
                        DraftVideoVO draftVideoVO = new DraftVideoVO();
                        GetPlayInfoRequest request = new GetPlayInfoRequest();
                        request.setVideoId(videoId);
                        GetPlayInfoResponse response = acsClient.getAcsResponse(request);
                        List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
                        String playURL = playInfoList.get(0).getPlayURL();
                        draftVideoVO.setVideoId(videoId);
                        draftVideoVO.setVideoUrl(playURL);
                        videoList.add(draftVideoVO);
                    }
                    vo.setVideoList(videoList);
                }
            }
            String topicIds = dynamic.getTopicIds();
            if (StringUtils.isNotBlank(topicIds)) {
                List<String> topicIdList = Arrays.asList(topicIds.split(","));
                List<TopicVO> topicList = topicService.listByIds(topicIdList).stream().map(t->{
                    Long id = t.getId();
                    String name = t.getName();
                    TopicVO topicVO = new TopicVO();
                    topicVO.setId(id);
                    topicVO.setName(name);
                    return topicVO;
                }).collect(Collectors.toList());
                vo.setTopicList(topicList);
            }
            vo.setViewPermission(vo.getViewPermission());
            return vo;
        }

        return null;
    }

    @Override
    public void dislike(DynamicDislikeDTO dto, Long userId) {
        Long dynamicId = dto.getDynamicId();
        Integer type = dto.getType();
        LambdaQueryWrapper<DynamicDislike> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(DynamicDislike::getDynamicId, dynamicId)
                .eq(DynamicDislike::getType, type)
                .eq(DynamicDislike::getUserId, userId);
        DynamicDislike dislike = dislikeService.getOne(wrapper);
        if (null != dislike) {
            throw new ServiceException("请勿重复提交！", HttpStatus.PARAMS_ERROR);
        }
        DynamicDislike dynamicDislike = new DynamicDislike();
        dynamicDislike.setDynamicId(dynamicId);
        dynamicDislike.setType(type);
        dynamicDislike.setUserId(userId);
        dislikeService.save(dynamicDislike);
    }

    @Override
    public void updatePermission(UpdatePermissionDTO dto, Long userId) {
        Long dynamicId = dto.getDynamicId();
        Integer viewPermission = dto.getViewPermission();
        Dynamic dynamic = this.getById(dynamicId);
        if (null == dynamic) {
            throw new ServiceException("动态不存在！", HttpStatus.PARAMS_ERROR);
        }
        if (!userId.equals(dynamic.getUserId())) {
            throw new ServiceException("不能修改别人的动态！", HttpStatus.PARAMS_ERROR);
        }

        dynamic.setViewPermission(viewPermission);
        this.updateById(dynamic);

    }



    @Override
    public DynamicDTO getDynamicById(Long currentUserId, Long id) {
        Dynamic dynamic = this.getById(id);
        if (null == dynamic){
            throw new ServiceException("该帖子已被删除！",HttpStatus.DATA_NOT_FOUND_ERROR);
        }
        Long circleId = dynamic.getCircleId();
        Long authorId = dynamic.getUserId();
        User user = userMapper.selectById(authorId);
        if (user == null){
            throw new ServiceException("该用户已被注销！",HttpStatus.USER_CANCEL_ERROR);
        }
        boolean follow = userFollowService.isFollow(currentUserId, authorId);
        DynamicDTO dto = patchData(dynamic, user, follow, currentUserId);
        Circle circle = circleService.getDetail(circleId);
        dto.setCircle(circle);
        return dto;
    }


    @SneakyThrows
    private void patchData(List<DynamicDTO> list,Long userId){
        List<String> allTopicIds = Lists.newLinkedList();
        List<Long> circleIds = list.stream().map(DynamicDTO::getCircleId).collect(Collectors.toList());
        List<Circle> circles = Lists.newLinkedList();
        if (CollectionUtil.isNotEmpty(circleIds)){
            circles = circleService.listByIds(circleIds);
        }
        for (DynamicDTO dto : list) {
            if (CollectionUtil.isNotEmpty(circles)){
                Optional<Circle> optional = circles.stream().filter(c -> c.getId().equals(dto.getCircleId())).findFirst();
                if (optional.isPresent()){
                    Circle circle = optional.get();
                    dto.setCircle(circle);
                    dto.setCircleType(circle.getType());
                    ParentCircleVO parentVO = new ParentCircleVO();
                    parentVO.setName(circle.getName());
                    parentVO.setCircleId(circle.getId());
                    circle.setParentCircle(parentVO);
                }
            }

            if (userId.equals(dto.getAuthorId())){
                dto.setIsMyself(Boolean.TRUE);
                dto.setIsFollow(Boolean.TRUE);
            }
            String picUrls = dto.getPicUrls();
            String topicIds = dto.getTopicIds();
            String videoIds = dto.getVideoIds();
            if (StringUtils.isNotBlank(picUrls)){
                List<String> pic = Arrays.asList(picUrls.split(","));
                dto.setPic(pic);
            }
            if (StringUtils.isNotBlank(videoIds)){
                List<VideoVO> videoVOS = Lists.newLinkedList();
                List<String> videoIdList = Arrays.asList(videoIds.split(","));
                for (String videoId : videoIdList) {
                    GetPlayInfoRequest request = new GetPlayInfoRequest();
                    request.setVideoId(videoId);
                    GetPlayInfoResponse response = acsClient.getAcsResponse(request);
                    List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
                    String playURL = playInfoList.get(0).getPlayURL();
                    VideoVO videoVO = new VideoVO();
                    videoVO.setVideoUrl(playURL);
                    videoVO.setCoverUrl(response.getVideoBase().getCoverURL());
                    videoVOS.add(videoVO);
                }
                dto.setVideoList(videoVOS);
            }
            if (StringUtils.isNotBlank(topicIds)){
                List<String> topicIdList = Arrays.asList(topicIds.split(","));
                allTopicIds.addAll(topicIdList);
            }
        }
        if (CollectionUtil.isNotEmpty(allTopicIds)) {
            List<Topic> topicList = topicService.listByIds(allTopicIds);
            for (DynamicDTO dto : list) {
                String topicIds = dto.getTopicIds();
                if (StringUtils.isNotBlank(topicIds)) {
                    List<String> topicIdList = Arrays.asList(topicIds.split(","));
                    List<TopicVO> topicVOS = topicList.stream().filter(t -> topicIdList.contains(t.getId().toString())).map(t1 -> {
                        TopicVO topicVO = new TopicVO();
                        topicVO.setName(t1.getName());
                        topicVO.setId(t1.getId());
                        return topicVO;
                    }).collect(Collectors.toList());
                    dto.setTopicList(topicVOS);
                }
            }
        }
    }


    @SneakyThrows
    private DynamicDTO patchData(Dynamic dynamic, User user, Boolean follow, Long currentUserId) {
        Long circleId = dynamic.getCircleId();
        DynamicDTO dto = new DynamicDTO();
        dto.setId(dynamic.getId());
        dto.setDynamicType(dynamic.getType());
        dto.setAudioUrl(dynamic.getAudioUrl());
        dto.setAudioTime(dynamic.getAudioTime());
        dto.setChatGroupAvatar(dynamic.getChatGroupAvatar());
        dto.setChatGroupId(dynamic.getChatGroupId());
        dto.setChatGroupName(dynamic.getChatGroupName());
        dto.setChatGroupUserCount(dynamic.getChatGroupUserCount());
        if (currentUserId.equals(dynamic.getUserId())){
            dto.setIsFollow(Boolean.TRUE);
            dto.setIsMyself(Boolean.TRUE);
        }
        Circle circle = circleService.getById(circleId);
        if (null != circle){
            dto.setCircleType(circle.getType());
            dto.setCircle(circle);
        }
        dto.setStatus(dynamic.getStatus());
        dto.setCircleId(circleId);
        dto.setAuthorId(user.getId());
        dto.setContent(dynamic.getContent());
        dto.setViewPermission(dynamic.getViewPermission());
        String imgUrls = dynamic.getImgUrls();
        if (StringUtils.isNotBlank(imgUrls)) {
            dto.setPic(Arrays.asList(imgUrls.split(",")));
        }
        String videoUrls = dynamic.getVideoIds();
        if (StringUtils.isNotBlank(videoUrls)){
            List<String> videoIdList = Arrays.asList(videoUrls.split(","));
            List<VideoVO> list = Lists.newLinkedList();
            for (String videoId : videoIdList) {
                GetPlayInfoRequest request = new GetPlayInfoRequest();
                request.setVideoId(videoId);
                GetPlayInfoResponse response = acsClient.getAcsResponse(request);
                List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
                String playURL = playInfoList.get(0).getPlayURL();
                VideoVO videoVO = new VideoVO();
                videoVO.setVideoUrl(playURL);
                videoVO.setCoverUrl(response.getVideoBase().getCoverURL());
                list.add(videoVO);
            }
            dto.setVideoList(list);
        }
        if (StrUtil.isBlank(dynamic.getContent())) {
            dto.setType(2);//只是图片
        }
        if (StrUtil.isBlank(dynamic.getImgUrls())) {
            dto.setType(1);//只有文字
        }
        if (StrUtil.isNotBlank(dynamic.getContent()) && StrUtil.isNotBlank(dynamic.getImgUrls())){
            dto.setType(3); //图片和文字
        }


        dto.setAddress(dynamic.getAddress());
        dto.setIsFollow(follow);
        dto.setAvatar(user.getAvatar());
        dto.setName(user.getNickname());

        //评论数
        Long commentCount = commentService.getCommentCount(dynamic.getId());
        dto.setCommentCount(commentCount);
        dto.setTime(dynamic.getUpdateTime());
        Long likeCount = dynamicUserLikeService.count(new LambdaQueryWrapper<CommunityDynamicUserLike>()
                .eq(CommunityDynamicUserLike::getDynamicId, dynamic.getId()));
        dto.setLikeCount(likeCount);
        CommunityDynamicUserLike userLike = dynamicUserLikeService.findUserLike(currentUserId, dynamic.getId());
        dto.setIsLike(userLike != null);
        //话题列表
        String topicIds = dynamic.getTopicIds();
        if (StringUtils.isNotBlank(topicIds)) {
            List<String> topicIdList = Arrays.asList(topicIds.split(","));
            List<TopicVO> topics = topicService.listByIds(topicIdList).stream().map(t -> {
                TopicVO vo = new TopicVO();
                vo.setId(t.getId());
                vo.setName(t.getName());
                return vo;
            }).collect(Collectors.toList());
            dto.setTopicList(topics);
        }
        return dto;
    }


}
